<?php

/**
 * This is the model class for table "app".
 *
 * The followings are the available columns in table 'app':
 * @property string $agentid
 * @property string $name
 * @property string $square_logo_url
 */
class App extends Base
{
	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return 'app';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive app inputs.
		return array(
			array('agentid, name, square_logo_url', 'required'),
			array('agentid', 'length', 'max'=>10),
			array('name', 'length', 'max'=>20),
			array('square_logo_url', 'length', 'max'=>150),
			// The following rule is used by search().
			// @todo Please remove those attributes that should not be searched.
			array('agentid, name, square_logo_url', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'agentid' => '企业应用id',
			'name' => '企业应用名称',
			'square_logo_url' => '企业应用方形头像url',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 *
	 * Typical usecase:
	 * - Initialize the model fields with values from filter form.
	 * - Execute this method to get CActiveDataProvider instance which will filter
	 * models according to data in model fields.
	 * - Pass data provider to CGridView, CListView or any similar widget.
	 *
	 * @return CActiveDataProvider the data provider that can return the models
	 * based on the search/filter conditions.
	 */
	public function search()
	{
		// @todo Please modify the following code to remove attributes that should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('agentid',$this->agentid,true);
		$criteria->compare('name',$this->name,true);
		$criteria->compare('square_logo_url',$this->square_logo_url,true);

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}

	/**
	 * Returns the static model of the specified AR class.
	 * Please note that you should have this exact method in all your CActiveRecord descendants!
	 * @param string $className active record class name.
	 * @return App the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
     * 下载微信应用
	*/
	public function downloadApp() {
	    try {
            $api = new WechatApi();
        } catch (CException $e) {
            $this->addError('app', $e->getMessage());
            return false;
        }
        $app_ret = $api->getApp();
        if ($app_ret['errcode'] != 0) {
            $this->addError('app', $app_ret['errmsg']);
            return false;
        }
        if (empty($app_ret['agentlist'])) {
            return true;
        }
        $app_data = $app_ret['agentlist'];
        $transaction = $this->getDbConnection()->beginTransaction();
        $ret = $this->getDbConnection()->createCommand()->truncateTable('app');
        if ($ret === false) {
            $transaction->rollback();
            $this->addError('app', '数据清除失败');
            return false;
        }
        $ret = $this->getDbConnection()->schema->commandBuilder
            ->createMultipleInsertCommand('app', $app_data)
            ->execute();
        if ($ret === false) {
            $transaction->rollback();
            $this->addError('app', '插入失败');
            return false;
        }
        $transaction->commit();
        //应用更新之后清除应用的缓存数据
        Yii::app()->cache->delete('app_list');
        return true;
    }

    /**
     * 获取所有应用，并缓存
    */
    public function getList() {
        $cache_key = 'app_list';
        $app_data = Yii::app()->cache->get($cache_key);
        if ($app_data !== false) {
            return $app_data;
        }
        $app_list = $this->findAll();
        if (empty($app_list)) {
            return array();
        }
        $app_data = array();
        foreach ($app_list as $app) {
            $app_data[] = $app->getAttributes();
        }
        Yii::app()->cache->set($cache_key,$app_data, 86400 * 30); //缓存一个月
        return $app_data;
    }

    public function pageListOpt(CDbCriteria $criteria) {
        $criteria->order = '';
        $criteria->select = 'agentid,name,square_logo_url';
    }
}
